package com.csi.juegoweb.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.csi.juegoweb.core.domain.Usuario;
import com.csi.juegoweb.dao.UsuarioDao;

@Repository("usuarioDao")
public class UsuarioDaoJdbc implements UsuarioDao {
	
	@Autowired
	private JdbcTemplate jdbcTemplateCore;

	@Override
	public List<Usuario> getUsuarios() {
		List<Usuario>  list=null;
		try {

			list=jdbcTemplateCore.query(
					"select id,name,username, email,password,usertype,block " +
					",sendEmail, gid, cast(registerDate as char) as registerDate, " +
					"cast(lastvisitDate as char)  as lastvisitDate, activation, params  from jos_users",
					new BeanPropertyRowMapper<Usuario>(Usuario.class));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public Usuario getUsuarioPorUsername(String usuario) {
		// TODO Auto-generated method stub

		return jdbcTemplateCore
				.queryForObject(
						"select id,name,username, email,password,usertype,block " +
						",sendEmail, gid, registerDate, lastvisitDate, activation," +
						" params from jos_users where username = ? ",
						new Object[] { usuario },
						new BeanPropertyRowMapper<Usuario>(Usuario.class));
	}

	@Override
	public List<Usuario> getListadoAmigos(String idUser) {
		List<Usuario> list=null;
		try {
			
			StringBuilder sql=new StringBuilder();
			
			sql.append(" select * from jos_users usert where usert.id in( ");
			sql.append(" select model.target as idUser from jos_community_activities model ");
			sql.append(" where model.actor='");
			sql.append(idUser);			
			sql.append("' union ");
			sql.append(" select model.target as idUser from jos_community_activities model ");
			sql.append(" where model.actor='");
			sql.append(idUser +"' )");
			
			list = jdbcTemplateCore.query(sql.toString(), new BeanPropertyRowMapper<Usuario>(Usuario.class));
			
			return list;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
}
